package com.example.deptempmanageservice.service;


import com.example.deptempmanageservice.dao.PositionMapper;
import com.myprojects.common.pojo.Department;
import com.myprojects.common.pojo.Position;
import com.myprojects.common.pojo.PositionExample;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PositionService {

    @Autowired
    PositionMapper positionMapper;

    public long countByExample(PositionExample example){
        return positionMapper.countByExample(example);
    }

    public int insert(Position record){
        return positionMapper.insert(record);
    }

    public int insertSelective(Position record){
        return positionMapper.insertSelective(record);
    }

    public int deleteLotsByPrimaryKey(List<Integer> list){
        return positionMapper.deleteLotsByPrimaryKey(list);
    }


    public PageInfo selectBySearchStr( Integer pageNum, Integer pageSize, String searchStr){
        List<Department> departmentList;//带职位的部门列表(要返回的数据)
        Integer id = null;
        int total;//查询结果总数

        PositionExample example;
        //如果搜索条件为空
        if ("".equals(searchStr.trim())) {
            //则搜索条件为空，这样就能直接查询全部
            example = null;
        } else {//否则就装配搜索条件
            example = new PositionExample();
            //尝试转换为数字，不行就当成查询字符串
            try {
                id = Integer.parseInt(searchStr);
                example.or().andIdEqualTo(id);
            } catch (Exception e) {
                // Position_name字段的模糊查询，这里的or()相当于sql里的 或 逻辑
                example.or().andPosition_nameLike("%" + searchStr + "%");
                // Brief字段的模糊查询，这里的or()相当于sql里的 或 逻辑
                example.or().andBriefLike("%" + searchStr + "%");
                // Department_name字段的模糊查询，这里的or()相当于sql里的 或 逻辑
                example.or().andDepartment_nameLike("%" + searchStr + "%");
            }
        }
        //非分页查询
        //如果要使用ID作为搜索条件
        if (id != null){
            departmentList = new ArrayList<>();
            Department department = selectByPrimaryKey(id);
            departmentList.add(department);
            total = (department != null) ? 1 : 0;
        }else {
            departmentList = selectByExample(example);
            total = departmentList.size();
        }

        //将departmentList切成分页段
        int start = (pageNum - 1) * pageSize;
        int stop = (pageNum - 1) * pageSize + pageSize;
        start = start < total ? start : total - pageSize;
        stop = stop < total ? stop : total;
        System.out.println("start:"+start+",stop:"+stop);
        if (total > 0) {
            departmentList = departmentList.subList(start,stop);
        }

        //使用PageInfo包装查询后的结果，需要将pageInfo交给页面
        //将查询出来用户信息加入pageInfo，并连续显示5页
        PageInfo pageInfo = new PageInfo(departmentList, 5);
        pageInfo.setTotal(total);

        return pageInfo;
    }

    /**
     * 该方法用于获取全部部门的列表(带职位列表)
     */
    public List<Department> selectAllPosition(){
        List<Department> departmentList;//带职位的部门列表(要返回的数据)
        //非分页查询
        departmentList = positionMapper.selectByExample(null);
        return departmentList;
    }

    public List<Department> selectByExample(PositionExample example){
        return positionMapper.selectByExample(example);
    }

    public Department selectByPrimaryKey(Integer id){
        return positionMapper.selectByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(Position record){
        return positionMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(Position record){
        return positionMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 该方法会检查该职位的所有属性是否合法
     * @return 携带错误信息的map，若map.size()>0则说明验证失败
     */
    public Map<String,Object> checkPosition(Position position, BindingResult result){
        Map<String , Object> errorMap = new HashMap<>();

        //先检查数据格式是否有误
        if (result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError error : fieldErrors){
                errorMap.put(error.getField(),error.getDefaultMessage());
            }
        }
        //再检查职位名有无重复
        PositionExample example = new PositionExample();
        example.createCriteria().andPosition_nameEqualTo(position.getPosition_name());
        long counts = countByExample(example);
        //如果该名字条目已存在，且职位不id存在，则说明为增加职位信息的情况
        if ( counts >= 1 && position.getId() == null){
            errorMap.put("position_name","职位名不能重复!");
        }
        //如果该名字条目已存在，且职位id存在，则说明为更新职位信息的情况(自己原先的名字重名和新改的名字重名)
        if ( counts >= 1 && position.getId() != null){
            String oldPosition_name = selectByPrimaryKey(position.getId()).getPositionList().get(0).getPosition_name();
            //若旧新职位名不一致，则不允许修改，因为这是新改的名字重名。否则则为与原先自己的名字重复的情况，则允许重名
            if (!oldPosition_name.equals(position.getPosition_name())){
                errorMap.put("position_name","职位名不能重复!");
            }
        }

        //返回errorMap
        return  errorMap;
    }

}
